﻿using System;
using System.Threading;
using System.Text;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.FEZ;

namespace RFM22b_Transceiver
{
    public class Program
    {
        public static void Main()
        {
            // Blink board LED

            Debug.EnableGCMessages(false);

            bool ledState = false;
            string PackText;
            int counter = 0;

            OutputPort led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.Di5, ledState);

            led.Write(true);

            RFM22b RadioModem = new RFM22b(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di7,  (Cpu.Pin)FEZ_Pin.Digital.Di6,  869.545);
            RFM22b.Channel StateChannel = RadioModem.NewChannel(0, 512, 32);
            RFM22b.Channel CmdChannel = RadioModem.NewChannel(1, 128, 64);
            RFM22b.Channel BinChannel = RadioModem.NewChannel(2, 512, 32);

            VirtualSerialPort PcConsole = new VirtualSerialPort();

            led.Write(false);
            Thread.Sleep(500);
            led.Write(true);

            while (true)
            {


                do
                {
                    PackText = StateChannel.RecvLine();

                    if (PackText.Length > 0)
                    {
                        led.Write(false);

                        PcConsole.Write("STATE " + PackText + "\r\n");
                        Debug.Print("STATE " + PackText);
                    }
                }
                while (PackText.Length > 0);

                do
                {
                    PackText = CmdChannel.RecvLine();

                    if (PackText.Length > 0)
                    {
                        led.Write(false);

                        PcConsole.Write("CMD " + PackText + "\r\n");
                        Debug.Print("CMD " + PackText);
                    }
                }
                while (PackText.Length > 0);

                do
                {
                    PackText = PcConsole.ReadLine();

                    if (PackText.Length > 0)
                    {
                        led.Write(false);

                        CmdChannel.SendLine(PackText);
                        Debug.Print("CMDSEND " + PackText);
                    }
                }
                while (PackText.Length > 0);

                if (counter > 50)
                {
                    counter = 0;
                    PcConsole.Write("GROUND " + RadioModem.LostPackets + "; " + RadioModem.RSSI + "\r\n");
                    Debug.Print("GROUND " + RadioModem.LostPackets + "; " + RadioModem.RSSI);
                }


                counter++;
                Thread.Sleep(100);

                led.Write(true);
            }
        }
    }
}
